<template>
	<view class="f16 feedbackSrc">
		<uni-forms ref="baseForm" :modelValue="formData">
			<uni-forms-item label="描述" required>
				<textarea class="text" focus maxlength="500" :value="formData.text" placeholder="请输入描述"
					style="width: 98%" @input="inputChange" />
			</uni-forms-item>
			<uni-forms-item label="项目" required>
				<uni-data-picker class="w100" placeholder="请选择项目" popup-title="请选择项目" :localdata="dataTree"
					v-model="formData.project_id" @change="onchange"></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item label="图片" v-if="videlValue.length === 0">
				<uni-file-picker :del-icon="false" ref="file" v-model="imageValue" mode="grid" @select="select"
					@success="success" @fail="fail" limit="1" />
			</uni-forms-item>
			<uni-forms-item label="视频" v-if="pathValue.length === 0">
				<uni-file-picker :del-icon="false" ref="file" v-model="videlValue" file-mediatype="video" mode="grid"
					@select="videoselect" limit="1" />
			</uni-forms-item>
			<uni-forms-item>
				<button type="primary" :disabled="isLoading" @click="submit" class="w100" :loading="isLoading">
					提交
				</button>
			</uni-forms-item>
		</uni-forms>
	</view>
</template>

<script>
	import store from "../../../store/index";
	export default {
		data() {
			return {
				dataTree: [],
				isLoading: false,
				formData: {
					description: "",
					location: "",
					project_id: "",
					text: ""
				},
				file: null,
				imageValue: [],
				pathValue: [],
				videoList: [],
				videlValue: []
			};
		},
		computed: {
			projects() {
				return store.state.projects;
			},
		},
		methods: {
			videoselect(e) {
				const tempFiles = e.tempFiles;
				for (let i = 0; i < tempFiles.length; i++) {
					this.videlValue.push({
						path: e.tempFiles[i].path,
					});
				}
			},
			uploadfile(path) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: "http://139.199.173.67" + this.$api.uploadFile, //仅为示例，非真实的接口地址
						filePath: path.path,
						name: "file",
						header: this.$aplsFormDataheader,
						success: (res) => {
							const result = JSON.parse(res.data);
							console.log(result, 57);
							if (result.status != 200) {
								reject("上传出错了");
								return;
							}
							const imgUrl = result.data;
							if (!imgUrl) {
								reject("");
								return;
							}
							resolve(imgUrl);
						},
						fail: (eee) => {
							console.log(eee);
							reject("上传失败");
						},
					});
				});
			},
			inputChange(e) {
				const value = e.detail.value;
				this.formData.description = value;
			},
			fail(e) {
				this.$errMessageToast(e.errMsg || e);
			},
			select(e) {
				const tempFiles = e.tempFiles;
				for (let i = 0; i < tempFiles.length; i++) {
					this.pathValue.push({
						path: e.tempFiles[i].path,
					});
				}
			},
			onchange(e) {
				this.formData.project_id = e.detail.value[0].value;
			},
			vaildType() {
				if (
					this.formData.description == "" ||
					this.formData.description == undefined
				) {
					throw new Error("请填写描述");
				}
				if (
					this.formData.project_id == "" ||
					this.formData.project_id == undefined
				) {
					throw new Error("请选择项目");
				}
				if (this.pathValue.length == 0 || this.videlValue.length == undefined) {
					throw new Error("请上传文件或者视频其中一个");
				}
				return true;
			},
			getLocation() {
				return new Promise((resolve, reject) => {
					uni.chooseLocation({
						success: function(res) {
							const location = res.name + res.address
							if (location != '' && location.length > 0) {
								resolve(location)
							} else {
								resolve("")
							}
						},
						fail: function(e) {
							console.log('fail');
							resolve("")
							this.$errMessageToast(e | e.message | '请求地理位置出错')
						}
					});
				})
			},
			async submit() {
				try {
					if (this.vaildType()) {
						const location = await this.getLocation()
						if (location.length === 0 || location === '' || location.trim().length === 0) {
							this.$errMessageToast('请选择地址再提交')
							return
						}
						this.formData.location = location
						this.isLoading = true;
						uni.showLoading({
							title: "正在上传...",
						});
						const path = this.pathValue[0] || this.videlValue[0];
						const imgUrl = await this.uploadfile(path);
						if (imgUrl) {
							try {
								const data = {
									file: imgUrl,
									location: this.formData.location,
									description: this.formData.description,
									project_id: this.formData.project_id
								}
								const result = await this.$request.request({
									url: this.$api.uploadProblem,
									data: JSON.stringify(data),
									header: this.$aplsjsonheader,
									isToast: true,
								});
								this.$errMessageToast('上传成功')
								uni.hideLoading()
								this.isLoading = false
								this.reset()
							} catch (e) {
								uni.hideLoading()
								this.isLoading = false
								this.$errMessageToast(e || e.message)
								//TODO handle the exception
							}
						}

					}
				} catch (errMessage) {
					this.isLoading = false;
					this.$errMessageToast(errMessage.message || errMessage);
				}
			},
			reset() {
				this.formData.description = ''
				this.formData.location = ''
				this.formData.project_id = ''
				this.formData.text = ''
				this.pathValue = []
				this.imageValue = []
				this.$refs.file.clearFiles()
			},
			getValue(data) {
				const arr = [...data];
				const list = arr.map((i) => {
					console.log(i.id, i.name);
					return {
						text: i.name,
						value: i.id,
					};
				});
				return list;
			},
			async getProjects(state) {
				const res = await this.$request.request({
					url: this.$api.getProject,
					method: "GET",
					isNotLoading: true,
				});
				this.dataTree = this.getValue(res);
			},
		},
		created() {
			this.getProjects()
		},
	};
</script>

<style scoped lang="less">
	.feedbackSrc {
		padding: 20rpx 20rpx 15rpx 20rpx;
		background-color: #fff;
		height: auto;

		.uni-forms-item__content {
			display: flex;
			align-items: center;
		}

		.w100 {
			width: 100%;
		}

		textarea {
			border: 1px solid #ccc;
			margin-right: 10px;
		}
	}
</style>
